import serial
import json

class SerialComm:
    def __init__(self, port="/dev/ttyS1", baudrate=115200, timeout=1):
        self.port = port
        self.baudrate = baudrate
        self.timeout = timeout
        self.serial = None
        self.connect()

    def connect(self):
        try:
            self.serial = serial.Serial(
                port=self.port,
                baudrate=self.baudrate,
                timeout=self.timeout
            )
            if self.serial.is_open:
                print(f"串口 {self.port} 连接成功")
            else:
                print(f"串口 {self.port} 打开失败")
        except serial.SerialException as e:
            print(f"串口连接错误: {e}")

    def send(self, data: str):
        """发送字符串数据（自动编码为 UTF-8）"""
        if self.serial and self.serial.is_open:
            self.serial.write(data.encode('utf-8'))

    def receive(self) -> str | None:
        """读取一行，并去除结尾换行符"""
        if self.serial and self.serial.is_open:
            return self.serial.readline().decode('utf-8', errors='ignore').strip()
        return None
    # def read_json(self) -> dict | None:
    #     """
    #     从串口读取数据片段，直到拼凑出完整的 JSON 字符串。
    #     成功解析后返回 dict;若暂未完整则返回 None。
    #     """
    #     # 持久缓冲区，保存尚未解析的片段
    #     if not hasattr(self, '_json_buffer'):
    #         self._json_buffer = ''

    #     # 尝试读取一行
    #     line = self.receive()
    #     if line is None:
    #         return None

    #     # 累积到缓冲区，并添加换行保证分隔
    #     self._json_buffer += line

    #     # 尝试解析当前缓冲区
    #     try:
    #         obj = json.loads(self._json_buffer)
    #         # 解析成功，清空缓冲区并返回对象
    #         self._json_buffer = ''
    #         return obj
    #     except json.JSONDecodeError as e:
    #         # 未完整——常见报错包含“Expecting value”或“Unterminated string”
    #         # 这里不打印错误以避免刷屏，也可以在开发时打印 e
    #         return None

    def close(self):
        if self.serial and self.serial.is_open:
            self.serial.close()
            print(f"🔌 串口 {self.port} 已关闭")


# if __name__ == "__main__":
#     # 创建串口对象并连接
#     serial_comm = SerialComm("/dev/ttyS1")

#     # 发送数据
#     serial_comm.send("Hello, World!")

#     # 接收数据
#     received_data = serial_comm.receive()
#     if received_data:
#         print(f"Received: {received_data}")

#     # 关闭串口连接